import { Button, Card, message, Tag, Form, Input, Select, Upload } from 'antd';
import { authUserAPI, fetchCertificatesTypeAPI, fetchUserInfoAPI } from '@/api/userAPI/userAPI';
import { useEffect, useMemo, useState } from 'react';
import type { GetProp, UploadProps, FormProps } from 'antd';
import { AuthFieldType, User as UserType } from '@/type/userType';
import './User.scss';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

export const User = () => {
  const [userInfo, setUserInfo] = useState<UserType>({} as UserType);
  const [certificates, setCertificates] = useState<{ label: string, value: string }[]>([]);
  const [imageUrl, setImageUrl] = useState<string>();
  const [certificatesType, setCertificatesType] = useState<string>('');
  const currentCertificatesType = useMemo(() => certificates.find(item => item.value === userInfo.certificatesType), [userInfo]);
  type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
  const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('请上传JPG或者PNG类型的文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('上传文件不能大于2MB!');
    }
    return isJpgOrPng && isLt2M;
  };


  const handleChange = (file: any) => {
    const response = file.file.response;
    if (response) {
      setImageUrl(response.data);
      message.success('上传文件成功');
    }
  };


  /**
   * @description 获取用户信息的回调函数
   * */
  const fetchUserInfo = async () => {
    try {
      const { data } = await fetchUserInfoAPI();
      setUserInfo(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 获取证件类型的回调函数
   * */
  const fetchCertificatesType = async () => {
    try {
      const { data } = await fetchCertificatesTypeAPI();
      setCertificates(data.map(item => ({ label: item.name, value: item.value })));
    } catch (error: any) {
      message.error(error.message);
    }
  };


  /**
   * @description 点击取消实名认证的接口
   * */
  const cancelAuth = () => {
    setUserInfo({
      ...userInfo,
      authStatus: 0,
    });
  };

  /**
   * @description 表单的提交事件
   * */
  const onFinish: FormProps<AuthFieldType>['onFinish'] = async (values) => {

    try {
      const data = { ...values, certificatesType, certificatesUrl: imageUrl };
      await authUserAPI(data);
      await fetchUserInfo();
      message.success('实名认证成功');
    } catch (error: any) {
      message.error(error.message);
    }
  };

  const getCertificateType = (value: string) => {
    setCertificatesType(value);
  };

  const renderUserInfo = () => {
    if (userInfo.authStatus === 1) {
      return (
        <>
          <p>用户姓名：{userInfo.name}</p>
          <p>证件类型：{currentCertificatesType?.label}</p>
          <p>证件号码：{userInfo.certificatesNo}</p>
          <p>手机号码：{userInfo.phone}</p>
          <p>
            <span>证件图片：</span>
            <img src={userInfo.certificatesUrl} alt="" />
          </p>
          <p>实名操作：<Button type="primary" danger onClick={cancelAuth}>重新认证</Button></p>
        </>
      );
    } else {
      return (
        <Form onFinish={onFinish}>
          <Form.Item label="用户姓名" name="name">
            <Input placeholder="请输入用户姓名"></Input>
          </Form.Item>
          <Form.Item label="证件类型">
            <Select placeholder="请选择证件类型" options={certificates} onChange={getCertificateType}></Select>
          </Form.Item>
          <Form.Item label="证件号码" name="certificatesNo">
            <Input placeholder="请输入证件号码"></Input>
          </Form.Item>
          <Form.Item label="上传证件">
            <Upload name="file" listType="picture-card" className="avatar-uploader" showUploadList={false} action="http://syt.atguigu.cn/api/oss/file/fileUpload?fileHost=userAuah" beforeUpload={beforeUpload} onChange={handleChange}>
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : <PlusOutlined></PlusOutlined>}
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button type="primary" danger onClick={() => setUserInfo({ ...userInfo, authStatus: 1 })}>取消</Button> <Button type="primary" danger>重置</Button> <Button type="primary" htmlType="submit">提交</Button>
          </Form.Item>
        </Form>
      );
    }
  };

  useEffect(() => {
    Promise.all([fetchUserInfo(), fetchCertificatesType()]);
  }, []);


  return (
    <div className="user">
      <div className="header">
        <h2>实名认证</h2>
      </div>
      <div className="tip">
        <Tag color="#2db7f5"><i style={{ color: '#fff' }} className="iconfont icon-zhuyi"></i><span>完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证</span></Tag>
      </div>
      <div className="card">
        <Card title="实名信息">
          {
            renderUserInfo()
          }
        </Card>

      </div>
    </div>
  );
};

export default User;
